package com.hcbd.tdwt.ui.xingyu.dialog;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;


import com.hcbd.tdwt.MainApp;
import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.AuthManger;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.util.AudioRecordUtil;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.FileUtil;
import com.hcbd.tdwt.view.MyProgressBar;
import com.pancoit.compression.ZDCompression;

import java.io.File;
import java.lang.ref.WeakReference;

public class VoiceDialog extends Dialog implements AudioRecordUtil.AudioInterface{
    public Context mContext;
    public OnCloseListener listener;
    public AnimationDrawable anim;
    public ImageView voiceAnim;
    public RelativeLayout voiceBtnBg;
    public LinearLayout microphoneBg;
    public MyProgressBar myProgressBar;
    public Drawable voiceDownBtnDrawable;
    public Drawable voiceDownBgDrawable;
    public Drawable voiceUpBtnDrawable;
    public Drawable voiceUpBgDrawable;
    public Drawable cancelSendingBg;
    public Drawable sendBg;
    public int voiceBtnBgHeight=0;
    public int seconds=0;
    public String audioFilePath;
    private float y1 = 0;
    private float y2 = 0;
    private int max=1377;
    private int progress=12;
    private int currentByteLen=0;
    private int totalByteLen=496000;
    private static class MyHandler extends Handler {
        //弱引用，在垃圾回收时，被回收
        WeakReference<VoiceDialog> dialogWeakReference;
        MyHandler(VoiceDialog dialog){
            this.dialogWeakReference=new WeakReference<>(dialog);
        }
        public void handleMessage(Message msg){
            VoiceDialog dialog=dialogWeakReference.get();
            if(msg.what==1){
                dialog.progress=dialog.currentByteLen/dialog.max;
                dialog.myProgressBar.setProgress(dialog.progress);
            }else if(msg.what==2){
                dialog.stopRecord();
                dialog.listener.onClick(dialog,dialog.audioFilePath);
            }
        }
    }
    private MyHandler handler;
    public void sendMsg(){
        Message message = new Message();
        if(currentByteLen==totalByteLen){
            message.what = 2;
        }else{
            message.what = 1;
        }
        handler.sendMessage(message);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_dialog);
        setCanceledOnTouchOutside(false);
        this.setCanceledOnTouchOutside(true);
        this.setCancelable(true);
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
        handler=new MyHandler(this);
    }
    public VoiceDialog(Context context, OnCloseListener listener) {
        super(context);
        this.mContext = context;
        this.listener = listener;
        voiceDownBtnDrawable= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.press_down, null);
        voiceUpBtnDrawable= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.voice_send, null);
        voiceDownBgDrawable= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.voice_btn_down_bg, null);
        voiceUpBgDrawable= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.voice_btn_bg, null);
        cancelSendingBg= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.cancel_sending_bg, null);
        sendBg= ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.microphone_bg, null);
        initMaxSeconds();

    }
    public void initMaxSeconds() {
        if (BeidouBoxParams.cardType == 5) {
            if(Constant.encoderCodeRate==ZDCompression.bitRate_2400){
                totalByteLen = 5*16000;
            }else if(Constant.encoderCodeRate==ZDCompression.bitRate_1200){
                totalByteLen = 11*16000;
            }else if(Constant.encoderCodeRate==ZDCompression.bitRate_700){
                totalByteLen = 19*16000;
            }else{
                totalByteLen = 31*16000;
            }
        } else if (BeidouBoxParams.cardType == 4) {
            if(Constant.encoderCodeRate==ZDCompression.bitRate_2400){
                totalByteLen = 3*16000;
            }else if(Constant.encoderCodeRate==ZDCompression.bitRate_1200){
                totalByteLen = 6*16000;
            }else if(Constant.encoderCodeRate==ZDCompression.bitRate_700){
                totalByteLen = 11*16000;
            }else{
                totalByteLen = 17*16000;
            }
        } else if (BeidouBoxParams.cardType == 3) {
            if(Constant.encoderCodeRate==ZDCompression.bitRate_1200){
                totalByteLen = 3*16000;
            }else if(Constant.encoderCodeRate==ZDCompression.bitRate_700){
                totalByteLen = 5*16000;
            }else{
                totalByteLen = 8*16000;
            }
        }
        max=totalByteLen/360;
    }
    @SuppressLint("ClickableViewAccessibility")
    private void initView(){
        voiceAnim=findViewById(R.id.voiceAnim);
        voiceBtnBg=findViewById(R.id.voiceBtnBg);
        microphoneBg=findViewById(R.id.microphoneBg);
        myProgressBar=findViewById(R.id.progress);
        myProgressBar.setProgressColor(ContextCompat.getColor(mContext,R.color.limegreen));
        myProgressBar.setProgressBackColor(ContextCompat.getColor(mContext,R.color.white));
        myProgressBar.setDrawable(voiceUpBtnDrawable);
        myProgressBar.setBoundWidth(0);
        myProgressBar.setProgressWidth(30);
        myProgressBar.setIsRote(false);
        anim = (AnimationDrawable) voiceAnim.getBackground();
        anim.start();
        voiceBtnBgHeight=voiceBtnBg.getHeight();
        AudioRecordUtil.getInstance().audioInterface=this;
    }

    @Override
    public void onReceive(int byteLen) {
        currentByteLen+=byteLen;
        sendMsg();
    }

    public interface OnCloseListener{
        void onClick(Dialog dialog, String file);
    }
    public void startRecord(){
        String suffix = ".pcm";
        audioFilePath= FileUtil.getAudioPcmFile()+ DateUtils.getDateShortSerial() + suffix;
        AudioRecordUtil.getInstance().init();
        AudioRecordUtil.getInstance().startPCM(audioFilePath);
    }
    //停止录制，资源释放
    public void stopRecord(){
        AudioRecordUtil.getInstance().stop();
        currentByteLen=0;
    }
    @Override
    public void dismiss(){
        super.dismiss();
        myProgressBar.setProgress(0);
    }

    public void dialogTouch(MotionEvent motionEvent){
        int action = motionEvent.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            y1 = motionEvent.getY();
            myProgressBar.setDrawable(voiceDownBtnDrawable);
            voiceBtnBg.setBackground(voiceDownBgDrawable);
            startRecord();
        } else if (action == MotionEvent.ACTION_UP) {
            y2 = motionEvent.getY();
            stopRecord();
            if(y1 - y2 > 150) {
                microphoneBg.setBackground(sendBg);
                File file=new File(audioFilePath);
                if(file.exists()){
                    file.delete();
                }
                dismiss();
            }else{
                listener.onClick(this,this.audioFilePath);
            }
            myProgressBar.setDrawable(voiceUpBtnDrawable);
            voiceBtnBg.setBackground(voiceUpBgDrawable);
        }else if(action== MotionEvent.ACTION_MOVE){
            y2 = motionEvent.getY();
            if(y1 - y2 > 150) {
                microphoneBg.setBackground(cancelSendingBg);
            }else{
                microphoneBg.setBackground(sendBg);
            }
        }
    }
    public void isSendVoice(Activity activity){
        if(checkPermissionInActivity(activity)){
            return;
        }
        if(!AuthManger.getAuthManger().isVoiceOnline()) {
            String str= ZDCompression.getInstance().getVOffInfo();
            if ("".equals(str) || str == null) {
                MainApp.getInstance().showMsg("库未初始化!");
                return;
            }
            String[] array = str.split(",");
            int usageCount=Integer.parseInt(array[0]);
            String endDate=array[2];
            String currentDate=DateUtils.getDateLongSerial();
            int code= DateUtils.dataContrast(currentDate, endDate);
            if (code==-1||code==0||0>=usageCount) {
                MainApp.getInstance().showMsg("库已过期,请授权");
                return;
            }
            if(BeidouBoxParams.card_model==2){
                MainApp.getInstance().showMsg("二代卡无法发送语音!");
                return;
            }
        }
        if(3> BeidouBoxParams.cardType) {
            MainApp.getInstance().showMsg("请选择3级卡及以上发语音!");
            return;
        }
        if(BeidouBoxParams.cardType==3&&Constant.encoderCodeRate==0){
            MainApp.getInstance().showMsg("3级卡无法发送2400bps语音,请在语音设置重新选择!");
            return;
        }
        show();
    }
    public boolean checkPermissionInActivity(Activity activity) {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.RECORD_AUDIO}, 5);
            return true;
        }else{
            return false;
        }
    }
    @Override
    public void show() {
        super.show();
        initView();
    }
}
